﻿using System;
using System.Collections.Generic;
using csvm.fileadapter.contract;
using System.IO;

namespace csvm.fileadapter
{
    public class FileAdapter : IFileAdapter
    {
        private long readBytes;

        public void ProcessReadFile(string filename) {

            using (var streamReader = File.OpenText(filename))
            {
                readBytes = 0;
                OnBuildRecords(GetLines(streamReader));
            }
        }

        private double GetPercentageOfReadBytes(long fileSize) {
            return Math.Min(readBytes / (double)fileSize * 100.0, 100.0);
        }

        private IEnumerable<string> GetLines(StreamReader streamReader) {
            string line;

            while ((line = streamReader.ReadLine()) != null) {
                readBytes += (line.Length + 2);
                OnProgressChanged(GetPercentageOfReadBytes(streamReader.BaseStream.Length));
                //OnProgressChanged(Math.Min(readBytes / (double) streamReader.BaseStream.Length * 100.0, 100.0));
                yield return line;
            }           
        }

        public event Action<double> OnProgressChanged;
        public event Action<IEnumerable<string>> OnBuildRecords;
    }
}
